import { Form, Input, InputNumber, Switch, Upload, message } from 'antd'
import { Rule } from 'antd/es/form'
import { InboxOutlined } from '@ant-design/icons'
import ThemeBtn from '@/components/antd-comp/theme-btn'
import {useState } from 'react'

interface FormPanelProps {
  form: any
  startVariables: any
  running: boolean
  localRunning: boolean
  handleRunEvent: () => void
}

const InputFormCont = ({ form, startVariables, running, localRunning, handleRunEvent }: FormPanelProps) => {
  const handleUpload = async (options: any) => {
    const { file, onSuccess, onError, onProgress } = options
    const formData = new FormData()
    
    formData.append('files', file)
    try {
      const response = await fetch('/api/v1/common/upload/batch', {
        method: 'POST',
        body: formData
      })

      if (response.ok) {
        const result = await response.json()
        onProgress({ percent: 100 }, file)
        onSuccess(result, file)
        return result.data[0]
      }
      throw new Error('上传失败')
    } catch (error) {
      message.error('文件上传失败')
      onError(error)
    }
  }

    // 添加文件上传状态
    const [uploadProgress, setUploadProgress] = useState<Record<string, number>>({})
    const [uploadStatus, setUploadStatus] = useState<Record<string, string>>({})

  return (
    <>
      <div className="px-8 py-3 bg-gray-50 rounded-md">
        <Form form={form} layout="vertical" initialValues={getInitialValues(startVariables)}>
          {startVariables && startVariables.variables
            ? startVariables.variables.map(item => {
                let inputNode
                const rules: Rule[] = [{ required: item.required, message: `${item.variable}不能为空` }]
                switch (item.type) {
                  case 'integer':
                    inputNode = (
                      <InputNumber
                        name={item.variable}
                        step={1}
                        precision={0}
                        min={-1000000000000}
                        max={1000000000000}
                        placeholder="请输入"
                        style={{ width: '400px' }}
                      />
                    )
                    break
                  case 'number':
                    inputNode = (
                      <InputNumber
                        name={item.variable}
                        min={-1000000000000}
                        max={1000000000000}
                        placeholder="请输入"
                        style={{ width: '400px' }}
                      />
                    )
                    break
                  case 'boolean':
                    inputNode = <Switch defaultChecked />
                    break
                  case 'file':
                    inputNode = (
                      <div className="upload-container" style={{ width: '400px' }}>
                        <Upload.Dragger
                          customRequest={handleUpload}
                          onChange={info => {
                            if (info.file.status === 'uploading') {
                              setUploadProgress(prev => ({
                                ...prev,
                                [item.variable]: info.file.percent || 0
                              }))
                            }
                            if (info.file.status === 'done') {
                              message.success(`${info.file.name} 上传成功`)
                              const fileUrls = info.fileList
                                .filter(file => file.status === 'done')
                                .map(file => file.response?.data[0])
                              form.setFieldValue(item.variable, fileUrls)
                            } else if (info.file.status === 'error') {
                              message.error(`${info.file.name} 上传失败`)
                            }
                          }}
                          multiple={false}
                          showUploadList={true}
                          accept={".doc,.docx,.pdf,.ppt,.pptx,.txt,.jpg,.jpeg,.png,.xlsx,.md,.csv,.json,.log"}
                        >
                          <p className="ant-upload-drag-icon">
                            <InboxOutlined />
                          </p>
                          <p className="ant-upload-text text-sm">点击或将文件拖拽到这里上传</p>
                          <p className="ant-upload-hint text-gray-400 text-xs">
                            支持 DOC、DOCX、PDF、PPT、PPTX、TXT、XLSX、Markdown、CSV、JSON、LOG
                          </p>
                        </Upload.Dragger>
                        <div className="text-gray-400 text-xs mt-2">
                          注：文件支持UTF-8编码格式
                        </div>
                      </div>
                    )
                    break
                  case 'array_file':
                    inputNode = (
                      <div className="upload-container">
                        <Upload.Dragger
                          customRequest={handleUpload}
                          onChange={info => {
                            if (info.file.status === 'uploading') {
                              setUploadProgress(prev => ({
                                ...prev,
                                [item.variable]: info.file.percent || 0
                              }))
                            }
                            if (info.file.status === 'done') {
                              message.success(`${info.file.name} 上传成功`)
                              const fileUrls = info.fileList
                                .filter(file => file.status === 'done')
                                .map(file => file.response?.data[0])
                              form.setFieldValue(item.variable, fileUrls)
                            } else if (info.file.status === 'error') {
                              message.error(`${info.file.name} 上传失败`)
                            }
                          }}
                          multiple={true}
                          showUploadList={true}
                          accept={".doc,.docx,.pdf,.ppt,.pptx,.txt,.jpg,.jpeg,.png,.xlsx,.md,.csv,.json,.log"}
                        >
                          <p className="ant-upload-drag-icon">
                            <InboxOutlined />
                          </p>
                          <p className="ant-upload-text text-sm">点击或将文件拖拽到这里上传</p>
                          <p className="ant-upload-hint text-gray-400 text-xs">
                            支持 DOC、DOCX、PDF、PPT、PPTX、TXT、XLSX、Markdown、CSV、JSON、LOG
                          </p>
                        </Upload.Dragger>
                        <div className="text-gray-400 text-xs mt-2">
                          注：文件支持UTF-8编码格式
                        </div>
                      </div>
                    )
                    break
                  case 'string':
                  case 'text':
                  default:
                    rules.push({ max: 1500, message: `输入不能大于1500个字符` })
                    inputNode = (
                      <Input
                        name={item.variable}
                        autoComplete="off"
                        placeholder="请输入"
                        style={{ width: '400px' }}
                      />
                    )
                }

                return (
                  <Form.Item
                    key={item.id}
                    name={item.variable}
                    label={`${item.variable}`}
                    required={item.required}
                    rules={rules}
                  >
                    {inputNode}
                  </Form.Item>
                )
              })
            : '开始节点参数错误'}
        </Form>
      </div>
      <div className="bottom-0 z-10 w-[100%] cursor-move border-black/5  bg-[#ffffff]">
        <div className="flex h-[56px] items-center justify-center px-4 pb-1 pt-1">
          <ThemeBtn loading={running && localRunning} className="w-[100%]" onClick={handleRunEvent}>
            试运行
          </ThemeBtn>
        </div>
      </div>
    </>
  )
}

const getInitialValues = (startVariables: any) => {
  if (!startVariables || !startVariables.variables) {
    return {}
  }

  return startVariables.variables.reduce((acc: any, item: any) => {
    if (item.type === 'boolean') {
      acc[item.variable] = true
    }
    return acc
  }, {})
}

export default InputFormCont